//
//  ApplySceneViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/19.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ApplySceneViewController.h"

#import "SelectDesignerViewController.h"
#import "EvaluateViewController.h"

#import "BoxSizeTableViewCell.h"

#import "FPCustomButton.h"

#import "ModuleSelectView.h"

@interface ApplySceneViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) UIImagePickerController *pickerController;
@property (nonatomic, strong) FPCustomButton *addPhotoBtn;
@property (nonatomic, strong) UIImage        *addImage;

@property (nonatomic, strong) ModuleSelectView  * moduleView;

@end

@implementation ApplySceneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"应用场景";
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    UIButton *connectBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49), ScreenX375(258), ScreenX375(49))];
    connectBtn.backgroundColor = REXADECIMALCOLOR(@"#ff9500");
    [connectBtn setTitle:@"有困难请联系我" forState:UIControlStateNormal];
    [connectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    connectBtn.titleLabel.font = Kfont(14);
    [self.view addSubview:connectBtn];
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(258), SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49), SCREEN_WIDTH - ScreenX375(258), ScreenX375(49))];
    nextBtn.backgroundColor = REXADECIMALCOLOR(@"#ed223b");
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextBtn.titleLabel.font = Kfont(14);
    [nextBtn addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
}

- (void)nextStep {
    if (!self.moduleView) {
        self.moduleView = [[ModuleSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.moduleView.isSelectFactory = NO;
        __weak __typeof(self) weakSelf = self;
        self.moduleView.chooseClick = ^(NSInteger index) {
            BoxSizeTableViewCell *cell = (BoxSizeTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
            if (index == 0) {
                EvaluateViewController *vc = [[EvaluateViewController alloc] init];
                vc.isDesign = YES;
                if (weakSelf.addImage) {
                    vc.pic = weakSelf.addImage;
                }
                vc.dict = @{@"goods_name":[(UITextField *)[weakSelf.view viewWithTag:100] text],@"long":cell.longField.text,@"wide":cell.widthField.text,@"height":cell.heightField.text,@"weight":[(UITextField *)[weakSelf.view viewWithTag:102] text],@"stack":[(UITextField *)[weakSelf.view viewWithTag:101] text],@"demand":[(UITextView *)[weakSelf.view viewWithTag:1000] text]};
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else {
                SelectDesignerViewController *vc = [[SelectDesignerViewController alloc] init];
                vc.chooseDesignerClick = ^(NSString *shopId, NSString *userId) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        EvaluateViewController *vc = [[EvaluateViewController alloc] init];
                        vc.isDesign = YES;
                        if (weakSelf.addImage) {
                            vc.pic = weakSelf.addImage;
                        }
                        vc.dict = @{@"goods_name":[(UITextField *)[weakSelf.view viewWithTag:100] text],@"long":cell.longField.text,@"wide":cell.widthField.text,@"height":cell.heightField.text,@"weight":[(UITextField *)[weakSelf.view viewWithTag:102] text],@"stack":[(UITextField *)[weakSelf.view viewWithTag:101] text],@"demand":[(UITextView *)[weakSelf.view viewWithTag:1000] text],@"shop_id":shopId,@"admin_id":userId};
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    });
                };
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
            [weakSelf.moduleView removeFromSuperview];
        };
        [self.moduleView modelArrayForView:@[@{@"name":@"系统推荐"},@{@"name":@"选择设计师"}]];
    }
    [kKeyWindow addSubview:self.moduleView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 3) {
        static NSString *cellId = @"connectCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        NSArray *noteArr = @[@"产      品：",@"堆叠层数：",@"产品重量："];
        NSArray *placeArr = @[@"请填写产品名称",@"请填写堆叠层数（1~10）",@"请填写产品重量（kg）"];
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(80), ScreenX375(44))];
        noteLabel.text = noteArr[indexPath.row];
        noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        noteLabel.font = Kfont(14);
        [cell addSubview:noteLabel];
        
        UITextField *connectField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(44))];
        connectField.placeholder = placeArr[indexPath.row];
        connectField.font = Kfont(14);
        if (indexPath.row == 1 || indexPath.row == 2) {
            connectField.keyboardType = UIKeyboardTypeNumberPad;
        }
        connectField.delegate = self;
        connectField.tag = 100 + indexPath.row;
        [cell addSubview:connectField];
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(44) - 0.5, SCREEN_WIDTH - ScreenX375(26), 0.5)];
        line.image = [UIImage imageNamed:@"虚线"];
        [cell addSubview:line];
        
        return cell;
    }else if (indexPath.row == 3) {
        static NSString *cellId = @"detailCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(100), ScreenX375(40))];
            noteLabel.text = @"工艺描述：";
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(14);
            [cell addSubview:noteLabel];
            
            UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(40), SCREEN_WIDTH - ScreenX375(26), ScreenX375(79))];
            textView.layer.cornerRadius = ScreenX375(5);
            textView.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
            textView.layer.borderWidth = 0.5;
            textView.clipsToBounds = YES;
            textView.tag = 1000;
            [cell addSubview:textView];
        }
        return cell;
    }else if (indexPath.row == 4) {
        static NSString *cellId = @"imageCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(100), ScreenX375(45))];
            noteLabel.text = @"参考模板：";
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(14);
            [cell addSubview:noteLabel];
            
            _addPhotoBtn = [FPCustomButton buttonWithType:UIButtonTypeCustom];
            _addPhotoBtn.frame = CGRectMake(ScreenX375(86), ScreenX375(15), ScreenX375(110), ScreenX375(110));
            [_addPhotoBtn setBackgroundImage:[UIImage imageNamed:@"虚线边框"] forState:UIControlStateNormal];
            [_addPhotoBtn setImage:[UIImage imageNamed:@"添加图片"] forState:UIControlStateNormal];
            [_addPhotoBtn setTitle:@"上次文件" forState:UIControlStateNormal];
            [_addPhotoBtn setTitleColor:RGB_COLOR(210,210,210) forState:UIControlStateNormal];
            _addPhotoBtn.titleLabel.font = Kfont(14);
            [_addPhotoBtn addTarget:self action:@selector(addPhotoClick) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:_addPhotoBtn];
        }
        return cell;
    }else {
        BoxSizeTableViewCell *cell = [BoxSizeTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 3) {
        return ScreenX375(44);
    }else if (indexPath.row == 3) {
        return ScreenX375(119);
    }else if (indexPath.row == 4) {
        return ScreenX375(125);
    }
    return ScreenX375(100);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)addPhotoClick {
    if (!self.pickerController) {
        self.pickerController = [[UIImagePickerController alloc] init];
        self.pickerController.delegate = self;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *send = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    UIAlertAction *get = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.pickerController.allowsEditing = YES;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    
    [alert addAction:cancel];
    [alert addAction:send];
    [alert addAction:get];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [_addPhotoBtn setBackgroundImage:image forState:UIControlStateNormal];
    [_addPhotoBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [_addPhotoBtn setTitle:@"" forState:UIControlStateNormal];
    _addImage = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickerController dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
